package cn.tedu.csmallpassport.security;

import cn.tedu.csmallpassport.mapper.AdminMapper;
import cn.tedu.csmallpassport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    AdminMapper mapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {


        AdminLoginInfoVO details = mapper.getLoginInfoByUsername(s);
        // 假设允许登录的账号是：root / 123456
//        if (!"root".equals(s)) {
//            return null;
//        }
        if (details == null) {
            return null;
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = details.getPermissions();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }

        AdminDetails adminDetails = new AdminDetails(
                details.getId(),
                details.getUsername(),
                details.getPassword(),
                details.getEnable() == 1,
                authorities
        );
//        UserDetails userDetails = User.builder()
//                .username(details.getUsername())
//                .password(details.getPassword()) // 期望是密文
//                .disabled(details.getEnable() == 0) // 账号禁用
////                .accountLocked(false) // 账号锁定
////                .accountExpired(false) // 账号过期
////                .credentialsExpired(false) // 凭证过期
//                .authorities("这是一个临时使用的山寨权限") // 权限
//                .build();
        return adminDetails;
    }

}
